﻿@using Pay.DTO;

@{
    ViewBag.Title = "确认支付";
    var img_url = ViewBag.img_url;
    Layout = "~/Views/Shared/_MallLayout.cshtml";
    var product = ViewBag.Product as product_dto;
    var shippingAddress = ViewBag.ShippingAddress as shippingaddress_dto;
    var orderModel = ViewBag.Checkout as token_check_out_model;
    int isShare = 0;
    string wxOpenId = ViewBag.WXOpenId;
    bool isLogin = ViewBag.IsLogin;
    string redirect_url = string.Empty;
    if (isLogin) {
        redirect_url = string.Format("{0}?returnUrl={1}", Url.Action("MyAdress", "User"), WebHelper.UrlEncode(Url.Action("ConfirmOrder", "Order") + "?t=1"));
    } else {
        redirect_url = string.Format("{0}?id={1}", Url.Action("Adress", "User"), (shippingAddress == null ? 0 : shippingAddress.id));
    }
    //var skuinfo= ViewBag.skuinfo as product_sku_dto;
}
<body class="page-shoppingCart page-cartConfirm">
    @Html.Partial("_PMallHead")
    <input type="hidden" id="isFromShare" value="@isShare" />
    <input type="hidden" id="wxOpenId" value="@wxOpenId" />
    <div class="orderAddress mb10">
        <a href="@redirect_url">
            <div class="box fn28">
                <i class="icon-site"></i>
                选择收货地址
                <i class="icon-go"></i>
            </div>
        </a>
        @if (shippingAddress != null) {
            <div class="box">
                <i class="icon-location"></i>
                <div class="lineBg"></div>
                <div class="top fn30 mb20">
                    <span class="name">@shippingAddress.shipto</span>
                    @shippingAddress.phone
                </div>
                <p class="col-gray fn26">@shippingAddress.region.region_name  @shippingAddress.address</p>
            </div>}
    </div>
    @{ bool is_sea = orderModel.orders.Any(s => s.is_seas);}
    <div class="mod-orderDetail lt-mb">
        <ul class="view">
            @foreach (var order in orderModel.orders) {
                <li>
                    <div class="shop" onclick="javascript: location.href='/DistributionMall/index2?shopId=@order.shop_id'">
                        <span class="shopImg mr20">
                            <img src="@(!string.IsNullOrEmpty(order.shop_logo)?  (img_url+order.shop_logo):"/Content/css/tokenmall/img/mallHome.png")" />
                        </span>
                        <span class="fn28 fn-left mr20">@(order.shop_id == 0 ? "拓垦官方旗舰店" : order.shop_name)</span>
                        <i class="icon-go4"></i>
                    </div>
                    @foreach (var item in order.order_items) {
                        <div class="innerItem bg-gray mb10" data-id="@item.product_id" data-sku-id="@item.sku_id">
                            <div class="img">
                                <img src="@item.product_main_img" />
                            </div>
                            <div class="text">
                                <p class="fn28 col-gray1">
                                    @item.product_name
                                </p>
                                <div class="col-gray mb10">
                                    <span class="mr20">@item.sku_name</span>
                                </div>
                                <div class="price col-gray">
                                    @if (item.price > 0) {
                                        <em class="fn22 col-red">￥</em>
                                        <span class="col-red fn28 itemPrice" data-option-price="@item.price.ToString("0.##")" data-option-activityPrice="@item.activity_price.ToString("0.##")">@item.activity_price.ToString("0.##")</span>
                                    }
                                    <input class="totalLi" type="hidden" value="@item.price.ToString("0.##")" />
                                    @if (item.red_drill > 0) {
                                        <span class="red-drill">
                                            @if (item.price > 0) {
                                                <em class="col-red fn28 red-drill">+</em>
                                            }
                                            <span class="col-red">
                                                <em class="fn28 itemDrill">@item.red_drill.ToString("0.######")</em>
                                                <em class="fn22"> 红钻</em>
                                            </span>
                                        </span>
                                    }
                                    <input class="totalRedrill" type="hidden" value="@item.red_drill.ToString("0.######")" />
                                    <div class="num" data-sku-id="@item.sku_id" data-product-id="@item.product_id">
                                        <span class="min">-</span>
                                        <input class="text_box" name="" type="text" value="@item.num" readonly unselectable="on" onfocus="this.blur()" />
                                        <span class="add">+</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    }
                    <div class="block fn28">
                        运费
                        <span class="fn-right">
                            <em class="fn22">￥</em><em class="freight">@order.freight.ToString("0.##")</em>
                            <a href="javascript:;" class="icon-tip2 fn-right"></a>
                        </span>
                    </div>
                    <div class="block fn28 message">
                        <span class="lable">买家留言</span>
                        <div class="hidden">
                            <input class="textInput fn-left remark" type="text" maxlength="100" placeholder="选填：填写已经和卖家协商好的内容">
                        </div>
                    </div>
                    <div class="block fn28 col-gray2">
                        <div class="fn-right">
                            <span class="mr20">共 <em class="order_count">@order.order_items.Count</em> 件商品</span>
                            <span>小计</span>&nbsp;
                            @if (order.total_amount > 0) {
                                <em class="col-red fn26">￥</em><em class="col-red fn32 innerItemTotal">@order.total_amount</em>
                            }

                            @if (order.total_red_drill > 0) {
                                <span class="red-drill">
                                    @if (order.total_amount > 0) {
                                        <em class="col-red fn28">+</em>
                                    }
                                    <span class="col-red">
                                        <em class="fn32 innerItemTotalDrill">@(order.total_red_drill.ToString("0.######"))</em>
                                        <em class="fn22"> 红钻</em>
                                    </span>
                                </span>

                            }
                        </div>
                    </div>
                </li>
            }
        </ul>
        @if (orderModel.product_red_drill > 0 && orderModel.is_all_drill > 1 && orderModel.total_red_drill > 0) {
            <div class="block bg-white fn28 money">
                <div class="common-row">
                    <div class="cell-left">只使用现金购买</div>
                    <div class="cell-right">
                        <span class="switch-off" id="bluetooth"></span>
                    </div>
                </div>
            </div>
        }
        @if (is_sea) {
            <div class="tishi fn26">
                <i class="icon-dang"></i>
                <div>
                    您购买的商品中有跨境的商品，跨境商品由于商品的特殊性，物流周期可能较长。
                </div>
            </div>}
        <br /><br /><br />
    </div>
    <div class="lt-bottom">
        <div class="right">
            <span class="fn28">
                总金额:
                <span class="col-red fn28 mr20">
                    @if (orderModel.total_amount > 0) {
                        <em class="col-red fn24">￥</em><em class="col-red fn36 total_amount">@orderModel.total_amount.ToString("0.##")</em>
                    }
                    @if (orderModel.product_red_drill > 0) {
                        <span class="red-drill">
                            @if (orderModel.total_amount > 0) {
                                <em class="col-red fn28">+</em>
                            }
                            <em class="fn36" id="total_red_drill">@orderModel.product_red_drill.ToString("0.######")</em>
                            <em class="fn22"> 红钻</em>
                        </span>
                    }
                </span>
            </span>
            <a href="javascript:;" class="ui-btn ui-btn-big ui-btn-red" id="buyNow">
                立即购买
            </a>
            <input type="hidden" id="user_total_drill" value="@orderModel.total_red_drill" />
            <input type="hidden" id="drill_opt_type" value="@orderModel.is_all_drill" />
        </div>
    </div>

    <!-- 点击购买弹窗 -->
    <div class="black trans_3"></div>
    <div class="mod-pop trans_3">
        <div class="top">
            <a href="javascript:;" class="icon-close"></a>
            <span class="fn-bold">确认订单</span>
        </div>
        <div class="contentPop">
            <div class="popItem">
                <div class="fn28 col-gray">订单金额</div>
                <div class="fn-center">
                    @if (orderModel.total_amount > 0) {
                        <span class="allPrice">@string.Format("¥{0}", orderModel.total_amount.ToString("0.##"))</span>
                    }
                    @if (orderModel.product_red_drill > 0) {
                        if (orderModel.total_amount > 0) {
                            <em class="col-red red-drill">+</em>
                        }
                        <span class="col-red red-drill">
                            <em class="fn36" id="pop_red_drill">@orderModel.product_red_drill.ToString("0.######")</em>
                            <em> 红钻</em>
                        </span>
                    }
                </div>
            </div>
            <div class="popItem">
                <i class="icon-go"></i>
                <span class="fn28 col-gray2">付款方式</span>
                <span class="fn-right payment">
                    <i class="icon-payment"></i>
                    <em class="fn30">微信支付</em>
                </span>
            </div>
            <div class="btnBox flex">
                <a href="javascript:confirmToPay();" class="ui-btn ui-btn-buy flex-1">
                    确认购买
                </a>
            </div>
        </div>
    </div>
    <script src="~/Scripts/token-common.js?v=001"></script>
    <script src="~/Scripts/tokenmall/honeySwitch.js"></script>
    <script>
        window.token = {
            pay_type: $('#drill_opt_type').val()
        };
        $(function () {
            window.token.init = function () {
                try {
                    if (browser.versions.ios) {
                        window.webkit.messageHandlers.NoShareUrl.postMessage('');
                    } else if (browser.versions.android) {
                        androidfuntion.NoShareUrl();
                    }
                } catch (e) {
                    //layer.msg("异常")
                }
                var windHeight = $(window).height();
                $('.mod-pop').css({ bottom: -windHeight });
                $('.black,.icon-close').click(function () {
                    $('.black').removeClass('cur');
                    $('.mod-pop').animate({ bottom: -windHeight });
                });
                //立即购买
                $('#buyNow').click(function () {
                    var product_red_drill = parseFloat($('#total_red_drill').html());
                    var user_total_drill = parseFloat($('#user_total_drill').val());
                    if (product_red_drill > user_total_drill) {
                        //pay_type 1:全红钻兑换，2：部分红钻兑换
                        var isAllRedrill = window.token.pay_type;
                        if (isAllRedrill == 1) {
                            layer.msg("您的可用红钻不足无法购买");
                            return;
                        } else if (isAllRedrill == 2) {
                            swal({
                                title: "您的可用红钻数量不足是否原价购买该商品？",
                                type: "warning",
                                showCancelButton: true,
                                confirmButtonColor: "",
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                closeOnConfirm: false
                                //设置closeOnConfirm: false，下面二次确认按钮被点击后才会关闭模态框
                            },
                                function (isConfirm) {
                                    if (isConfirm) {
                                        //todo:调起支付
                                        swal.close();
                                        $('.black').addClass('cur');
                                        $('.mod-pop').animate({ bottom: 0 });
                                        window.token.pay_type = 3;
                                        $('#bluetooth').click();
                                    } else {
                                        //取消不做任何处理
                                    }
                                });
                        } else {
                            $('.black').addClass('cur');
                            $('.mod-pop').animate({ bottom: 0 });
                        }
                    } else {
                        $('.black').addClass('cur');
                        $('.mod-pop').animate({ bottom: 0 });
                    }
                });
                //加商品数量
                $(".add").click(function () {
                    var t_parent = $(this).parent('.num');
                    var t = $(this).parent().find('input[class*=text_box]');
                    $.get("/DistributionMall/GetProductCalculate", { id: t_parent.attr("data-product-id"), skuId: t_parent.attr("data-sku-id") }, function (response) {
                        if (response.result_code == 1000) {
                            var data = response.data;
                            var num = parseInt(t.val()) + 1;
                            if (data.max_quantity > 0 && num > data.max_quantity) {
                                layer.msg("活动商品每人 限购" + data.max_quantity + "件");
                                return;
                            }
                            if (num > data.stock) {
                                layer.msg("库存不足");
                                return;
                            }
                            t.val(num);
                            window.token.numTotal();
                            window.token.setTotal();
                        }
                    });
                });
                //扣减商品数量
                $(".min").click(function () {
                    var t = $(this).parent().find('input[class*=text_box]');
                    t.val(parseFloat(t.val()) - 1)
                    if (parseFloat(t.val()) < 1) {
                        t.val(1);
                    }
                    window.token.numTotal();
                    window.token.setTotal();
                });
                // 运费点击弹窗
                $('.icon-tip2').click(function () {
                    swal({
                        title: "",
                        text: "快递城市的不同运费有可能也会有所差异，如果需要补充邮费商家会主动联系您!",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "",
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        closeOnConfirm: false
                        // 设置closeOnConfirm: false，下面二次确认按钮被点击后才会关闭模态框
                    });
                });
                window.token.numTotal();
                window.token.setTotal();
            };
            window.token.numTotal = function () {
                $(".view li .innerItem").each(function () {
                    var itemPrice = $(this).find('span[class*=itemPrice]').text();
                    itemPrice = (itemPrice == '' ? 0 : itemPrice);
                    var s = parseFloat($(this).find('input[class*=text_box]').val()) * parseFloat(itemPrice);
                    $(this).find(".totalLi").val(toDecimalRoundNoZero(s, 2));
                    var itemDrill = $(this).find('em[class*=itemDrill]').text();
                    itemDrill = (itemDrill == '' ? 0 : itemDrill);
                    var total_drill = parseFloat($(this).find('input[class*=text_box]').val()) * parseFloat(itemDrill);
                    $(this).find(".totalRedrill").val(toDecimalRoundNoZero(total_drill, 6));
                });
            };
            window.token.setTotal = function () {
                var total = 0, total_drill = 0;
                $(".view li").each(function () {
                    var sum = 0;
                    //统计每个店铺红钻小计
                    var temp_drill = 0;
                    var oSelf = $(this);
                    oSelf.find('.innerItem').each(function () {
                        sum = sum + parseFloat($(this).find('.totalLi').val()); // 店铺产品价格总和
                        total_drill = total_drill + parseFloat($(this).find('.totalRedrill').val());//统计所有店铺红钻总计
                        temp_drill = temp_drill + parseFloat($(this).find('.totalRedrill').val());
                    });
                    sum = sum + parseFloat($(this).find('.freight').text()); //加运费
                    $(this).find('.innerItemTotal').html(toDecimalRoundNoZero(sum, 2));//小计
                    $(this).find('.innerItemTotalDrill').html(toDecimalRoundNoZero(temp_drill, 6));//红钻小计
                    total += sum;
                });
                $('.total_amount').html(toDecimalRoundNoZero(total, 2));//总计
                $('.allPrice').text('¥' + toDecimalRoundNoZero(total, 2));//订单金额
                $('#pop_red_drill,#total_red_drill').html(toDecimalRoundNoZero(total_drill, 6));//订单红钻总数
            };
            window.token.init();
            window.token.cash_pay = function () {
                //纯现金支付
                $(".view li").each(function () {
                    var sum = 0;
                    var oSelf = $(this);
                    oSelf.find('.innerItem').each(function () {
                        var price = $(this).find('.itemPrice').attr('data-option-price');
                        $(this).find('.itemPrice').text(price);
                    });
                });
                //隐藏红钻部分元素
                $('.red-drill').each(function () {
                    $(this).addClass('none');
                });
                this.pay_type = 3;
                window.token.numTotal();
                window.token.setTotal();
            };
            window.token.red_drill_pay = function () {
                //红钻+现金支付
                $(".view li").each(function () {
                    var sum = 0;
                    var oSelf = $(this);
                    oSelf.find('.innerItem').each(function () {
                        var price = $(this).find('.itemPrice').attr('data-option-activityPrice');
                        $(this).find('.itemPrice').text(price);
                    });
                });
                //显示红钻部分元素
                $('.red-drill').each(function () {
                    $(this).removeClass('none');
                });
                this.pay_type = 2;
                window.token.numTotal();
                window.token.setTotal();
            };
        });
    </script>

    <script type="text/javascript">
        function isWxBrowser() {
            var result = false;
            //判断浏览器，在微信内打开，提示请在其他浏览器中打开
            var browser = {
                versions: function () {
                    var u = navigator.userAgent, app = navigator.appVersion;
                    return {
                        //移动终端浏览器版本信息
                        trident: u.indexOf('Trident') > -1, //IE内核
                        presto: u.indexOf('Presto') > -1, //opera内核
                        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                        iPad: u.indexOf('iPad') > -1, //是否iPad
                        webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部,
                        WeiXin: u.match(/MicroMessenger/i) == "MicroMessenger" //是否为微信客户端
                    };
                }(),
                language: (navigator.browserLanguage || navigator.language).toLowerCase()
            };
            if (browser.versions.mobile) {
                //判断是否是移动设备打开。browser代码在下面
                var ua = navigator.userAgent.toLowerCase();
                //获取判断用的对象
                if (ua.match(/MicroMessenger/i) == "micromessenger") { //微信中打开
                    return true;
                }
            }
            return result;
        }

        $(function () {
            var wxOpenId = $("#wxOpenId").val();
            if (isWxBrowser() == true && (wxOpenId == undefined || wxOpenId == "")) {
                window.location.href = '@Url.Action("GetWXOpenIdAuth", "CommonTokenMall")?returnUrl=@System.Web.HttpUtility.UrlEncode(Request.Url.ToString())';
            }
            if (isWxBrowser() == false && wxOpenId != undefined && wxOpenId != "") {
                $("#wxOpenId").val('');
                wxOpenId = "";
            }
        })

        function onBridgeReady(wcPayModel) {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": wcPayModel.appid,
                    "timeStamp": wcPayModel.timestamp,
                    "nonceStr": wcPayModel.noncestr,
                    "package": wcPayModel.package,
                    "signType": "MD5",
                    "paySign": wcPayModel.paysign
                },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                        window.location.href = '/MyOrder/OrderList?type=1';
                    } else {
                        window.location.href = '/MyOrder/OrderList?type=1';
                    }
                }
            );
        }

        var isConfirmToPayDisable = false;
        function confirmToPay() {
            if (!isConfirmToPayDisable) {
                isConfirmToPayDisable = true;
                var data = {
                    total_amount: $(".total_amount").html(),
                    orders: [],
                    pay_type: window.token.pay_type
                };
                $(".view li").each(function () {
                    var oSelf = $(this);
                    var order = {
                        remark: $(this).find('input[class*=remark]').val(),
                        order_items:[]
                    };
                    oSelf.find('.innerItem').each(function () {
                        var order_item = {
                            product_id: $(this).attr('data-id'),
                            sku_id: $(this).attr('data-sku-id'),
                            quantity: $(this).find('input[class*=text_box]').val()
                        };
                        order.order_items.push(order_item);
                    });
                    data.orders.push(order);
                });
                if (data.orders.length == 0) { layer.msg("没有结算商品"); return; }
                $.ajax({
                    type: 'POST',
                    async: false,
                    url: '/Order/Pay',
                    data: data,
                    success: function (result) {
                        if (result.result_code == 1000) {
                            if (isWxBrowser() == true) {//微信浏览器打开，公众号支付
                                //layer.msg("请在微信外浏览器打开完成支付");
                                //return false;
                                var wcPayModel = $.parseJSON(result.result_msg);
                                if (typeof WeixinJSBridge == "undefined") {
                                    if (document.addEventListener) {
                                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                    } else if (document.attachEvent) {
                                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                    }
                                } else {
                                    onBridgeReady(wcPayModel);
                                }
                            } else {//h5支付
                                window.location.href = result.result_msg;
                            }
                        } else if (result.result_code == 2000) {
                            layer.msg("购买跨境商品，收货地址填写有误。");
                            setTimeout(function () {
                                window.location.href = "/User/Adress?id=" + result.result_msg + "&returnUrl=@WebHelper.UrlEncode(Url.Action("ConfirmOrder", "Order") + "?t=1")";
                            }, 1500);
                            isConfirmToPayDisable = false;
                        }
                        else {
                            layer.msg(result.result_msg);
                            isConfirmToPayDisable = false;
                        }
                    },
                    error: function () {
                        isConfirmToPayDisable = false;
                    }
                });
            }
        }
    </script>
</body>
